# events.py
from .exts import soc
from flask_socketio import emit, join_room, leave_room
from .models import *

# 全局变量
rooms_list = set()
rooms_chat = set()


# 上线
@soc.on('connect')
def test_connect():
    # print('connected')
    emit('connected', {"message": "连接成功!!!"})
    print('connected')


@soc.on('one')
def save_user_id(data):
    # print(data)
    user_id = data.get('user_id')
    # 使用 Flask-SocketIO 提供的 join_room 函数
    join_room(user_id)
    # 如果你有一个全局的房间列表 rooms_list 想要跟踪用户加入的房间，可以这样做：
    rooms_list.add(user_id)
    print(f'{user_id}上线了')


@soc.on('disconnect')
def handle_leave_room(data):
    user_id = data['user_id']
    leave_room(user_id)
    rooms_list.discard(user_id)
    print(f'退出了{user_id}房间中')


@soc.on('send_message')
def handle_send_message(data):
    # 从客户端接收到的数据中提取消息内容和房间号
    user_id = data['user_id']
    for_id = data['for_id']
    content = data['content']
    # picture = data['picture']
    bools = 0
    user = str(user_id) + 'chat'
    # 判断房间号是否存在
    if for_id in rooms_list:  # 如果用户在线
        print(f"房间 {for_id} 已在线")
        # 向指定房间的所有客户端发送消息
        if user in rooms_chat:  # 如果用户在聊天栏目内
            discord_state = False
            bools = 1
        else:
            discord_state = True
            bools = 2
    else:
        print(f"房间 {for_id} 不在线")
        discord_state = True
    discord = Discord(
        discord_text=content,
        discord_state=discord_state,
        discord_picture=None,
        discord_reception=for_id,
        discord_user=user_id
    )
    db.session.add(discord)
    db.session.commit()
    dis = Discord.query.filter_by(discord_user=user_id,
                                  discord_reception=for_id,
                                  discord_state=True).all()
    if bools == 1:
        emit('room_in_message', {'message': f'{user_id}向{for_id}用户发的消息',
                                 'chats': [discord]},
             room=user)
    elif bools == 2:
        emit('room_out_message', {'message': f'{user_id}向{for_id}用户发的消息',
                                  'discord_number': len(dis)}, room=for_id)
    else:
        print(f"用户{for_id} 不在线。")


@soc.on('chat')
def handle_chat(data):
    user_id = data['user_id']
    user = user_id + 'chat'
    join_room(user)
    print(f'{user}进入了聊天')
    # 查询该用户所以的未读消息
    dis = Discord.query.filter_by(discord_reception=user_id,
                                  discord_state=True).all()
    # 将未读消息发送给该用户
    emit('room_in', {'message': f'{user_id}进入了聊天',
                     'chats': [dis]},
         room=user)
    # 将这些未读消息的状态变为已读
    for i in dis:
        i.discord_state = False
    db.session.commit()


@soc.on('leave_chat')
def handle_leave_chat(data):
    user_id = data['user_id']
    user = str(user_id) + 'chat'
    leave_room(user)
    print(f'{user}退出了聊天')
